// packageD/o2o/recommendlist/recommendlist.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    show_num:'',
    keyword:'',
    arr:[],
    datas:[],
    goload: true,
    page: 1,
    total_page: 0,
    result:[],
    store_id:'',
    first:'',
    second:'',
    option1: [],
    option2: [],
    activeNames: "",
    showPopup: false,
    chooseGoods: [], //选中的商品
    language: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      store_id: options.store_id,
    });
    this.getStoreInfo();
    this.getdata();
  },
  onChange(event) {
    this.setData({
      activeNames: event.detail,
    });
  },
  openPopup() {
    this.setData({
      showPopup: true,
    })
  },
  onClose() {
    this.setData({
      showPopup: false,
    })
  },
  add() {
    console.log(this.data.result);
    let json = {
      store_id: this.data.store_id,
      choose_goods: this.data.result,
    };
    this.tapPush(json);
  },
  tapPush(json) {
    let urlStr = app.getNetAddresss(
      "plugin.nearby-store-goods.frontend.controllers.goods.index"
    );
    app._postNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        console.log(res);
        if (res.result == 1) {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
            success: function () {
              wx.navigateBack({
                delta: 1,
              });
            },
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  goText() {
    wx.navigateTo({
      url:
        "/packageD/o2o/recommendtext/recommendtext?store_id=" +
        this.data.store_id +
        "&&show_num=" +
        this.data.show_num,
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({ language: language.en });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log(2222222);
  },
  bindscroll() {
    var that = this;
    let url='';
    let json={};
    console.log(this.data.first,55555555555);
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      this.data.page = this.data.page + 1;
      // if(this.data.first.length<=0){
      //   json = { page: this.data.page,store_id: this.data.store_id };
      //   url= "plugin.store-cashier.frontend.store.near-by-goods.index";
      // }else{
        json = { page: this.data.page,store_id: this.data.store_id,category:{
          parentid:this.data.first,
          childid:this.data.second
        }};
        url= "plugin.store-cashier.frontend.store.near-by-goods.get-goods-list";
      // }
      app._postNetWork({
        url: app.getNetAddresss(url),
        data: json,
        success: function (resdata) {
          var res = resdata.data;
          console.log(res);
          if (res.result == 1) {
            let newDatas = that.data.datas.concat(res.data.list.data);
            for(let item of that.data.result) {
              for(let citem of newDatas) {
                if(item == citem.id) {
                  citem.isAdd = true
                }
              }
            }
            that.setData({
              datas: newDatas
            })
            
          } else {
            that.setData({
              page: that.data.page - 1,
            })
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  getdata() {
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.store-cashier.frontend.store.near-by-goods.get-store-goods"
    );
    app._postNetWork({
      url: urlStr,
      data: {
        store_id: that.data.store_id,
      },
      success: function (resdata) {
        var res = resdata.data;
        console.log(res);
        if (res.result == 1) {
          that.setData({
            show_num: res.data.show_num,
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getStoreInfo() {
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.store-cashier.frontend.store.near-by-goods.index"
    );
    app._postNetWork({
      url: urlStr,
      data: {
        store_id: that.data.store_id,
        page: this.data.page,
      },
      success: function (resdata) {
        var res = resdata.data;
        console.log(res);
        if (res.result == 1) {
          let newOption1 = [];
          res.data.category.forEach((item,index,key)=>{
            let json={};
            json.text=item.name;
            json.value=item.id;
            newOption1.push(json);
          });
          that.setData({
            // datas: res.data.goods_data.data,
            arr: res.data.category,
            option1: newOption1,
            current_page: res.data.goods_data.current_page,
            last_page: res.data.goods_data.last_page,
          });

          if(that.data.option1.length) {
            that.changeCategory(that.data.option1[0].value,0)
          }
          console.log(res.data.goods_data);
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  changeCategory(item,index_){
    let value = item;
    let index = index_
    if(index_ == undefined) {
      value = item.currentTarget.dataset.value;
      index = item.currentTarget.dataset.index;
    }
    console.log(item,index_, index_ == undefined , 'valuevalue');
    let newOption1 = this.data.option1;
    for(let item of newOption1) {
      item.actived = false
    }
    newOption1[index].actived = true;
    this.setData({
      option1: newOption1,
      page: 1,
      option2: []
    })
    let newOption2 = [];
    this.data.arr.forEach((item,index,key)=>{
      if(item.id==value){
        let obj=item.childrens;
        obj.forEach((list,index,key)=>{
          let o={};
          o.text=list.name;
          o.value=list.id;
          newOption2.push(o);
        });
      }
    });
    newOption2.unshift({
      text: "全部",
      value: ""
    })
    newOption2[0].actived = true;
    let that = this;
    that.setData({
      option2: newOption2,
      first: value
    })
    let json = { store_id: that.data.store_id,page:that.data.page,category:{
      parentid:that.data.first,
      childid:''
    }};
    app._postNetWork({
      url: app.getNetAddresss("plugin.store-cashier.frontend.store.near-by-goods.get-goods-list"),
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let newDatas = res.data.list.data;
          for(let item of that.data.result) {
            for(let citem of newDatas) {
              if(item == citem.id) {
                citem.isAdd = true
              }
            }
          }

          that.setData({
            datas: newDatas,
            total_page: res.data.list.last_page
          })
          if (!that.data.total_page) {
            that.setData({
              total_page: 0
            })
          }
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  changeSecond(item,index_){
    let value = item;
    let index = index_
    if(index_ == undefined) {
      value = item.currentTarget.dataset.value;
      index = item.currentTarget.dataset.index;
    }
    console.log(item,index_, index_ == undefined , 'valuevalue');
    
    let newOption2 = this.data.option2;
    for(let item of newOption2) {
      item.actived = false;
    }
    newOption2[index].actived = true;
    this.setData({
      page: 1,
      second: value,
      option2: newOption2
    })
    let that = this;
    let json = { store_id: that.data.store_id,page:that.data.page,category:{
      parentid:that.data.first,
      childid:that.data.second
    }};
    app._postNetWork({
      url: app.getNetAddresss("plugin.store-cashier.frontend.store.near-by-goods.get-goods-list"),
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let newDatas = res.data.list.data;
          for(let item of that.data.result) {
            for(let citem of newDatas) {
              if(item == citem.id) {
                citem.isAdd = true
              }
            }
          }
          console.log(res,that.data,newDatas,888888);

          that.setData({
            datas: newDatas,
            total_page: res.data.list.last_page,
            activeNames: false
          })
          if (!that.data.total_page) {
            that.setData({
              total_page: 0
            })
          }
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  // 选中商品
  clickAdd(item) {
    let index = item.currentTarget.dataset.index;

    let newDatas = this.data.datas;
    newDatas[index].isAdd = true;
    let newChooseGoods = newDatas.filter(item  => item.isAdd);
    newChooseGoods  = this.reduceData([...this.data.chooseGoods,...newChooseGoods]);
    let newResult = newChooseGoods.map(citem => citem.id);
    this.setData({
      datas: newDatas,
      chooseGoods: newChooseGoods,
      result: newResult
    })
    console.log(this.data.chooseGoods,newResult,'chooseGoodschooseGoods')
  },
  // 删除商品
  clickDel(item) {
    let id = item.currentTarget.dataset.id;
    let index = item.currentTarget.dataset.index;

    let newDatas = this.data.datas;
    newDatas[index].isAdd = false;
    let newChooseGoods  = this.data.chooseGoods;
    let index_ = ""
    for(let [key , item] of newChooseGoods.entries()) {
      if(item.id == id) {
        index_ = key;
      }
    }
    newChooseGoods.splice(index_,1);
    let newResult = newChooseGoods.map(citem => citem.id);
    this.setData({
      datas: newDatas,
      chooseGoods: newChooseGoods,
      result: newResult
    })
  },
  // 删除选中的数据
  delChooseGoods(item) {
    let id = item.currentTarget.dataset.id;
    let index = item.currentTarget.dataset.index;

    let newDatas = this.data.datas;
    let newChooseGoods = this.data.chooseGoods;
    newChooseGoods.splice(index,1);
    for(let [index_ , item] of newDatas.entries()) {
      if(item.id == id) {
        newDatas[index_].isAdd = false;
      }
    }
    let newResult = newChooseGoods.map(citem => citem.id);
    this.setData({
      datas: newDatas,
      chooseGoods: newChooseGoods,
      result: newResult
    })
  },
  // 清空选中数据
  clearChooseGoods() {
    let newDatas = this.data.datas;
    for(let [index_ , item] of newDatas.entries()) {
      newDatas[index_].isAdd = false;
    }
    this.setData({
      datas: newDatas,
      chooseGoods: [],
      result: []
    })
  },
  // 过滤重复数据
  reduceData(person) {
    let obj = {};
    let peon = person.reduce((cur,next) => {
        obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
        return cur;
    },[]) //设置cur默认类型为数组，并且初始值为空的数组
    return peon
  }
});
